package com.study.webapp.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class TimeLock implements Runnable {

	private static ReentrantLock lock = new ReentrantLock();

	@Override
	public void run() {
		try {
			// 获取锁成功则返回true
			// tryLock方法，设置获取3次失败就放弃获取，第一个获取锁就睡眠5秒，第二个线程就获取不到锁被迫停止
			// 如果tryLock()方法不传入任何参数，那么获取锁的线程不会等待锁，则立即返回false。
			if (lock.tryLock(3, TimeUnit.SECONDS)) {
				Thread.sleep(5000);
			} else {
				System.out.println(Thread.currentThread().getName() + "获取锁失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 如果当前线程持有锁，则释放锁。
			if (lock.isHeldByCurrentThread()) {
				System.out.println(Thread.currentThread().getName() + "释放锁了");
				lock.unlock();
			}
		}

	}

	public static void main(String[] args) {
		TimeLock t = new TimeLock();
		Thread t1 = new Thread(t, "thread-1");
		Thread t2 = new Thread(t, "thread-2");
		t1.start();
		t2.start();
	}

}
